package tables

import (
	"strconv"

	"github.com/GoAdminGroup/go-admin/context"
	"github.com/GoAdminGroup/go-admin/modules/db"
	form2 "github.com/GoAdminGroup/go-admin/plugins/admin/modules/form"
	"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
	"github.com/GoAdminGroup/go-admin/template/types"
	"github.com/GoAdminGroup/go-admin/template/types/form"
	editType "github.com/GoAdminGroup/go-admin/template/types/table"

	"app/models"
	"app/utils"
)

type Variant struct {
	ID           string
	VariantName  string
	CategoryName string
}

func getVariantNameById(id string) string {
	var variant Variant
	err := models.Orm.Table("seed_variant").Select("seed_variant.name as variant_name, seed_category.name as category_name").
		Joins("left join seed_category on seed_variant.category_id = seed_category.id").
		Where("seed_variant.id = ?", id).
		Scan(&variant).Error
	if err != nil {
		return ""
	}
	return variant.CategoryName + "-" + variant.VariantName
}

func getVariantOptions() types.FieldOptions {
	var options types.FieldOptions
	var variants []Variant
	models.Orm.Table("seed_variant").
		Select("seed_variant.id, seed_variant.name as variant_name, seed_category.name as category_name").
		Joins("left join seed_category on seed_variant.category_id = seed_category.id").
		Find(&variants)
	for _, variant := range variants {
		options = append(options, types.FieldOption{
			Text:  variant.CategoryName + "-" + variant.VariantName,
			Value: variant.ID,
		})
	}
	return options
}

func GetOrdersTable(ctx *context.Context) table.Table {

	orders := table.NewDefaultTable(table.DefaultConfigWithDriver("mysql"))

	info := orders.GetInfo()
	info.SetFilterFormLayout(form.LayoutTwoCol)
	// 获取当前用户信息
	//user := auth.Auth(ctx)
	//
	//if user.CheckRole("SowingManager") {
	//	// 播种管理员
	//	// 订单状态只显示 2-待播种, 3-已播种, 4-待分棚, 5-已分棚
	//	info.WhereRaw("`order_status` in (2, 3, 4, 5)")
	//}
	//
	//if user.CheckRole("GreenhouseManager") {
	//	// 大棚管理员
	//	// 订单状态只显示  5-已分棚 , 6-待分苗床, 7-已分苗床, 8-待出苗, 9-已出苗
	//	info.WhereRaw("`order_status` in (5, 6, 7, 8, 9)")
	//}

	info.SetSortField("created_at").SetSortDesc()
	info.AddField("Id", "id", db.Int).
		FieldFilterable().
		FieldSortable()
	info.AddField("创建时间", "created_at", db.Timestamp).
		FieldFilterable().
		FieldSortable()
	info.AddField("客户", "customer", db.Varchar).
		FieldFilterable().
		FieldSortable()
	info.AddField("订单名称", "name", db.Varchar).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("电话", "phone", db.Varchar).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("订单备注", "remark", db.Varchar).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("是否关注", "care", db.Tinyint).
		FieldDisplay(func(model types.FieldModel) interface{} {
			switch model.Value {
			case "0": // 启用
				return "不关注"
			case "1": // 弃用
				return "关注"
			default: // 未知
				return "不关注"
			}
		}).
		FieldFilterable(types.FilterType{FormType: form.SelectSingle}).
		FieldFilterOptions(types.FieldOptions{
			{Text: "关注", Value: "1"},
			{Text: "不关注", Value: "0"},
		}).
		FieldEditAble(editType.Select).FieldEditOptions(types.FieldOptions{
		{Text: "关注", Value: "1"},
		{Text: "不关注", Value: "0"},
	}).
		FieldSortable()
	info.AddField("种子型号", "seed_variant_id", db.Varchar).
		FieldDisplay(func(value types.FieldModel) interface{} {
			return getVariantNameById(strconv.FormatInt(value.Row["seed_variant_id"].(int64), 10))
		}).
		FieldFilterable(types.FilterType{FormType: form.SelectSingle}).
		FieldFilterOptions(getVariantOptions()).
		FieldSortable()
	info.AddField("种子数量", "seed_quantity", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("种子盘数", "tray_number", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("每盘数量", "unit_number", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("种子备注", "seed_remark", db.Varchar).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("预计播种日期", "estimated_sowing_date", db.Date).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("实际播种日期", "actual_sowing_date", db.Date).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("预计出苗日期", "estimated_seedling_date", db.Date).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("实际出苗日期", "actual_seedling_date", db.Date).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("已播种数量", "sowed_quantity", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("已分配苗床数量", "allocated_seedbed_quantity", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("订单要求的提苗数量", "required_seedling_quantity", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("订单要求的提苗盘数", "required_seedling_tray", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("订单要求的提苗每盘数量", "required_seedling_unit", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("已提苗数量", "delivered_quantity", db.Int).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("订单总金额", "total_amount", db.Decimal).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("已收款金额", "received_amount", db.Decimal).
		FieldFilterable().
		FieldSortable().
		FieldEditAble()
	info.AddField("支付情况", "payment_status", db.Tinyint).
		FieldDisplay(func(model types.FieldModel) interface{} {
			switch model.Value {
			case "1": // 启用
				return "支付中"
			case "2": // 弃用
				return "支付完成"
			case "-1": // 弃用
				return "未支付"
			default: // 未知
				return "未知"
			}
		}).
		FieldFilterable(types.FilterType{FormType: form.SelectSingle}).
		FieldFilterOptions(types.FieldOptions{
			{Text: "支付中", Value: "1"},
			{Text: "支付完成", Value: "2"},
			{Text: "未支付", Value: "-1"},
			{Text: "未知", Value: "0"},
		}).
		FieldEditAble(editType.Select).FieldEditOptions(types.FieldOptions{
		{Text: "支付中", Value: "1"},
		{Text: "支付完成", Value: "2"},
		{Text: "未支付", Value: "-1"},
		{Text: "未知", Value: "0"},
	}).
		FieldSortable()

	info.AddField("订单状态", "order_status", db.Tinyint).
		FieldDisplay(func(model types.FieldModel) interface{} {
			switch model.Value {
			case "1": // 启用
				return "已下单"
			case "2": // 弃用
				return "待播种"
			case "3": // 弃用
				return "已播种"
			case "4": // 弃用
				return "待分棚"
			case "5": // 弃用
				return "已分棚"
			case "6": // 弃用
				return "待分苗床"
			case "7": // 弃用
				return "已分苗床"
			case "8": // 弃用
				return "待出苗"
			case "9": // 弃用
				return "已出苗"
			case "10": // 弃用
				return "待收款"
			case "11": // 弃用
				return "已全部收款"
			default: // 未知
				return "未知"
			}
		}).
		FieldFilterable(types.FilterType{FormType: form.SelectSingle}).
		FieldFilterOptions(types.FieldOptions{
			{Text: "已下单", Value: "1"},
			{Text: "待播种", Value: "2"},
			{Text: "已播种", Value: "3"},
			{Text: "待分棚", Value: "4"},
			{Text: "已分棚", Value: "5"},
			{Text: "待分苗床", Value: "6"},
			{Text: "已分苗床", Value: "7"},
			{Text: "待出苗", Value: "8"},
			{Text: "已出苗", Value: "9"},
			{Text: "待收款", Value: "10"},
			{Text: "已全部收款", Value: "11"},
			{Text: "未知", Value: "0"},
		}).
		FieldEditAble(editType.Select).FieldEditOptions(types.FieldOptions{
		{Text: "已下单", Value: "1"},
		{Text: "待播种", Value: "2"},
		{Text: "已播种", Value: "3"},
		{Text: "待分棚", Value: "4"},
		{Text: "已分棚", Value: "5"},
		{Text: "待分苗床", Value: "6"},
		{Text: "已分苗床", Value: "7"},
		{Text: "待出苗", Value: "8"},
		{Text: "已出苗", Value: "9"},
		{Text: "待收款", Value: "10"},
		{Text: "已全部收款", Value: "11"},
		{Text: "未知", Value: "0"},
	}).
		FieldSortable()
	info.AddField("更新时间", "updated_at", db.Timestamp).
		FieldSortable()

	info.SetTable("orders").SetTitle("订单管理").SetDescription("Orders")

	formList := orders.GetForm()
	formList.AddField("Id", "id", db.Int, form.Default).
		FieldDisableWhenCreate()
	formList.AddField("订单名称", "name", db.Varchar, form.Text)
	formList.AddField("客户", "customer", db.Varchar, form.Text)
	formList.AddField("电话", "phone", db.Varchar, form.Text)
	formList.AddField("订单备注", "remark", db.Varchar, form.Text)

	formList.AddField("种子型号", "seed_variant_id", db.Int, form.SelectSingle).FieldOptions(getVariantOptions()).FieldHelpMsg("请选择种子型号")
	formList.AddField("种子数量", "seed_quantity", db.Int, form.Number)
	formList.AddField("种子盘数", "tray_number", db.Int, form.Number)
	formList.AddField("每盘数量", "unit_number", db.Int, form.Number)
	formList.AddField("种子备注", "seed_remark", db.Varchar, form.Text)
	formList.AddField("是否关注", "care", db.Tinyint, form.Radio).
		// radio的选项，Text代表显示内容，Value代表对应值
		FieldOptions(types.FieldOptions{
			{Text: "关注", Value: "1"},
			{Text: "不关注", Value: "0"},
		}).FieldDefault("0")
	formList.AddField("预计播种日期", "estimated_sowing_date", db.Date, form.Date)
	formList.AddField("实际播种日期", "actual_sowing_date", db.Date, form.Date)
	formList.AddField("预计出苗日期", "estimated_seedling_date", db.Date, form.Date)
	formList.AddField("实际出苗日期", "actual_seedling_date", db.Date, form.Date)
	formList.AddField("已播种数量", "sowed_quantity", db.Int, form.Number)
	formList.AddField("已分配苗床数量", "allocated_seedbed_quantity", db.Int, form.Number)
	formList.AddField("订单要求的提苗数量", "required_seedling_quantity", db.Int, form.Number)
	formList.AddField("订单要求的提苗盘数", "required_seedling_tray", db.Int, form.Number)
	formList.AddField("订单要求的提苗每盘数量", "required_seedling_unit", db.Int, form.Number)
	formList.AddField("已提苗数量", "delivered_quantity", db.Int, form.Number)
	formList.AddField("订单总金额", "total_amount", db.Decimal, form.Text)
	formList.AddField("已收款金额", "received_amount", db.Decimal, form.Text)
	formList.AddField("支付情况", "payment_status", db.Tinyint, form.Radio).
		// radio的选项，Text代表显示内容，Value代表对应值
		FieldOptions(types.FieldOptions{
			{Text: "支付中", Value: "1"},
			{Text: "支付完成", Value: "2"},
			{Text: "未支付", Value: "-1"},
			{Text: "未知", Value: "0"},
		}).FieldDefault("0")
	formList.AddField("订单状态", "order_status", db.Tinyint, form.Radio).
		// radio的选项，Text代表显示内容，Value代表对应值
		FieldOptions(types.FieldOptions{
			{Text: "已下单", Value: "1"},
			{Text: "待播种", Value: "2"},
			{Text: "已播种", Value: "3"},
			{Text: "待分棚", Value: "4"},
			{Text: "已分棚", Value: "5"},
			{Text: "待分苗床", Value: "6"},
			{Text: "已分苗床", Value: "7"},
			{Text: "待出苗", Value: "8"},
			{Text: "已出苗", Value: "9"},
			{Text: "待收款", Value: "10"},
			{Text: "已全部收款", Value: "11"},
			{Text: "未知", Value: "0"},
		}).FieldDefault("0")
	formList.AddField("创建时间", "created_at", db.Timestamp, form.Datetime).
		FieldDisableWhenUpdate().
		FieldHide().FieldNowWhenInsert()
	formList.AddField("修改时间", "updated_at", db.Timestamp, form.Datetime).
		FieldDisableWhenCreate().
		FieldHide().FieldNowWhenUpdate()

	formList.SetInsertFn(func(values form2.Values) error {
		// 获取客户ID和种子型号ID
		customer := values.Get("customer")
		seedVariantId := values.Get("seed_variant_id")

		// 查询种子型号名称
		seedVariantName := getVariantNameById(seedVariantId)

		// 拼接订单名称
		orderName := customer + "-" + seedVariantName

		// 设置订单名称
		values["name"] = []string{orderName}

		// 模型实例
		o := &models.Orders{}

		if values.Get("customer") != "" {
			o.Customer = values.Get("customer")
		}
		if values.Get("seed_variant_id") != "" {
			o.SeedVariantID = utils.ToInt(values.Get("seed_variant_id"))
		}
		if values.Get("seed_quantity") != "" {
			o.SeedQuantity = utils.ToInt(values.Get("seed_quantity"))
		}
		if values.Get("tray_number") != "" {
			o.TrayNumber = utils.ToInt(values.Get("tray_number"))
		}
		if values.Get("unit_number") != "" {
			o.UnitNumber = utils.ToInt(values.Get("unit_number"))
		}
		if values.Get("care") != "" {
			o.Care = values.Get("care") == "1"
		}
		if values.Get("sowed_quantity") != "" {
			o.SowedQuantity = utils.ToInt(values.Get("sowed_quantity"))
		}
		if values.Get("allocated_seedbed_quantity") != "" {
			o.AllocatedSeedbedQuantity = utils.ToInt(values.Get("allocated_seedbed_quantity"))
		}
		if values.Get("required_seedling_quantity") != "" {
			o.RequiredSeedlingQuantity = utils.ToInt(values.Get("required_seedling_quantity"))
		}
		if values.Get("required_seedling_tray") != "" {
			o.RequiredSeedlingTray = utils.ToInt(values.Get("required_seedling_tray"))
		}
		if values.Get("required_seedling_unit") != "" {
			o.RequiredSeedlingUnit = utils.ToInt(values.Get("required_seedling_unit"))
		}
		if values.Get("delivered_quantity") != "" {
			o.DeliveredQuantity = utils.ToInt(values.Get("delivered_quantity"))
		}
		if values.Get("total_amount") != "" {
			o.TotalAmount = utils.ToFloat64(values.Get("total_amount"))
		}
		if values.Get("received_amount") != "" {
			o.ReceivedAmount = utils.ToFloat64(values.Get("received_amount"))
		}
		if values.Get("payment_status") != "" {
			o.PaymentStatus = utils.ToInt(values.Get("payment_status"))
		}
		if values.Get("order_status") != "" {
			o.OrderStatus = utils.ToInt(values.Get("order_status"))
		}
		if values.Get("phone") != "" {
			o.Phone = utils.ToString(values.Get("phone"))
		}
		if values.Get("name") != "" {
			o.Name = utils.ToString(values.Get("name"))
		}
		if values.Get("seed_remark") != "" {
			o.SeedRemark = utils.ToString(values.Get("seed_remark"))
		}
		if values.Get("remark") != "" {
			o.Remark = utils.ToString(values.Get("remark"))
		}

		// 解析所有的可能存在的时间字段
		if values.Get("estimated_sowing_date") != "" {
			o.EstimatedSowingDate = utils.ToDateV2(values.Get("estimated_sowing_date"))
		}
		if values.Get("actual_sowing_date") != "" {
			o.ActualSowingDate = utils.ToDateV2(values.Get("actual_sowing_date"))
		}
		if values.Get("estimated_seedling_date") != "" {
			o.EstimatedSeedlingDate = utils.ToDateV2(values.Get("estimated_seedling_date"))
		}
		if values.Get("actual_seedling_date") != "" {
			o.ActualSeedlingDate = utils.ToDateV2(values.Get("actual_seedling_date"))
		}

		// 插入新的订单记录
		res := models.Orm.Create(o)
		return res.Error
	})

	formList.SetUpdateFn(func(values form2.Values) error {
		ID := values.Get("id")
		o := new(models.Orders)
		res := models.Orm.First(o, ID)
		if res.Error != nil {
			return res.Error
		}
		// 获取客户ID和种子型号ID

		customer := values.Get("customer")
		seedVariantId := values.Get("seed_variant_id")

		if customer == "" {
			customer = o.Customer
		}

		if seedVariantId == "" {
			seedVariantId = strconv.Itoa(o.SeedVariantID)
		}

		// 查询种子型号名称
		seedVariantName := getVariantNameById(seedVariantId)

		// 拼接订单名称
		orderName := customer + "-" + seedVariantName

		// 设置订单名称
		values["name"] = []string{orderName}

		if values.Get("customer") != "" {
			o.Customer = values.Get("customer")
		}
		if values.Get("seed_variant_id") != "" {
			o.SeedVariantID = utils.ToInt(values.Get("seed_variant_id"))
		}
		if values.Get("seed_quantity") != "" {
			o.SeedQuantity = utils.ToInt(values.Get("seed_quantity"))
		}
		if values.Get("tray_number") != "" {
			o.TrayNumber = utils.ToInt(values.Get("tray_number"))
		}
		if values.Get("unit_number") != "" {
			o.UnitNumber = utils.ToInt(values.Get("unit_number"))
		}
		if values.Get("care") != "" {
			o.Care = values.Get("care") == "1"
		}

		if values.Get("sowed_quantity") != "" {
			o.SowedQuantity = utils.ToInt(values.Get("sowed_quantity"))
		}
		if values.Get("allocated_seedbed_quantity") != "" {
			o.AllocatedSeedbedQuantity = utils.ToInt(values.Get("allocated_seedbed_quantity"))
		}
		if values.Get("required_seedling_quantity") != "" {
			o.RequiredSeedlingQuantity = utils.ToInt(values.Get("required_seedling_quantity"))
		}
		if values.Get("required_seedling_tray") != "" {
			o.RequiredSeedlingTray = utils.ToInt(values.Get("required_seedling_tray"))
		}
		if values.Get("required_seedling_unit") != "" {
			o.RequiredSeedlingUnit = utils.ToInt(values.Get("required_seedling_unit"))
		}
		if values.Get("delivered_quantity") != "" {
			o.DeliveredQuantity = utils.ToInt(values.Get("delivered_quantity"))
		}
		if values.Get("total_amount") != "" {
			o.TotalAmount = utils.ToFloat64(values.Get("total_amount"))
		}
		if values.Get("payment_status") != "" {
			o.PaymentStatus = utils.ToInt(values.Get("payment_status"))
		}
		if values.Get("order_status") != "" {
			o.OrderStatus = utils.ToInt(values.Get("order_status"))
		}
		if values.Get("phone") != "" {
			o.Phone = utils.ToString(values.Get("phone"))
		}
		if values.Get("name") != "" {
			o.Name = utils.ToString(values.Get("name"))
		}
		if values.Get("seed_remark") != "" {
			o.SeedRemark = utils.ToString(values.Get("seed_remark"))
		}
		if values.Get("remark") != "" {
			o.Remark = utils.ToString(values.Get("remark"))
		}

		// 解析所有的可能存在的时间字段
		if values.Get("estimated_sowing_date") != "" {
			o.EstimatedSowingDate = utils.ToDateV2(values.Get("estimated_sowing_date"))
		}
		if values.Get("actual_sowing_date") != "" {
			o.ActualSowingDate = utils.ToDateV2(values.Get("actual_sowing_date"))
		}
		if values.Get("estimated_seedling_date") != "" {
			o.EstimatedSeedlingDate = utils.ToDateV2(values.Get("estimated_seedling_date"))
		}
		if values.Get("actual_seedling_date") != "" {
			o.ActualSeedlingDate = utils.ToDateV2(values.Get("actual_seedling_date"))
		}

		// 插入新的订单记录
		res = models.Orm.Save(o)
		return res.Error
	})

	formList.SetTable("orders").SetTitle("订单管理").SetDescription("Orders")

	return orders
}
